package com.example.managemyself.api.controller;

import com.example.managemyself.api.entity.Task;
import com.example.managemyself.api.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 任务控制器
 */
@RestController
@RequestMapping("/api/tasks")
@CrossOrigin(origins = "*")
public class TaskController {
    
    @Autowired
    private TaskService taskService;
    
    /**
     * 创建新任务
     */
    @PostMapping
    public ResponseEntity<?> createTask(@Valid @RequestBody Task task) {
        try {
            Task createdTask = taskService.createTask(task);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdTask);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * 根据ID获取任务
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getTaskById(@PathVariable Long id) {
        Optional<Task> task = taskService.getTaskById(id);
        if (task.isPresent()) {
            return ResponseEntity.ok(task.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 更新任务
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateTask(@PathVariable Long id, @Valid @RequestBody Task taskDetails) {
        try {
            Task updatedTask = taskService.updateTask(id, taskDetails);
            return ResponseEntity.ok(updatedTask);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * 删除任务
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteTask(@PathVariable Long id) {
        try {
            taskService.deleteTask(id);
            return ResponseEntity.ok(Map.of("message", "任务删除成功"));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * 完成任务
     */
    @PutMapping("/{id}/complete")
    public ResponseEntity<?> completeTask(@PathVariable Long id) {
        try {
            Task completedTask = taskService.completeTask(id);
            return ResponseEntity.ok(completedTask);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * 更新任务状态
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateTaskStatus(
            @PathVariable Long id,
            @RequestBody Map<String, String> statusRequest) {
        
        String statusStr = statusRequest.get("status");
        if (statusStr == null) {
            return ResponseEntity.badRequest().body(Map.of("error", "状态不能为空"));
        }
        
        try {
            Task.TaskStatus status = Task.TaskStatus.valueOf(statusStr.toUpperCase());
            Task updatedTask = taskService.updateTaskStatus(id, status);
            return ResponseEntity.ok(updatedTask);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of("error", "无效的状态值"));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * 获取用户的所有任务
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Task>> getUserTasks(@PathVariable Long userId) {
        List<Task> tasks = taskService.getUserTasks(userId);
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 分页获取用户任务
     */
    @GetMapping("/user/{userId}/page")
    public ResponseEntity<Page<Task>> getUserTasksPage(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        
        Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                   Sort.by(sortBy).descending() : 
                   Sort.by(sortBy).ascending();
        
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<Task> tasks = taskService.getUserTasks(userId, pageable);
        
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 根据状态获取用户任务
     */
    @GetMapping("/user/{userId}/status/{status}")
    public ResponseEntity<List<Task>> getUserTasksByStatus(
            @PathVariable Long userId,
            @PathVariable Task.TaskStatus status) {
        
        List<Task> tasks = taskService.getUserTasksByStatus(userId, status);
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 分页根据状态获取用户任务
     */
    @GetMapping("/user/{userId}/status/{status}/page")
    public ResponseEntity<Page<Task>> getUserTasksByStatusPage(
            @PathVariable Long userId,
            @PathVariable Task.TaskStatus status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        
        Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                   Sort.by(sortBy).descending() : 
                   Sort.by(sortBy).ascending();
        
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<Task> tasks = taskService.getUserTasksByStatus(userId, status, pageable);
        
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 根据优先级获取用户任务
     */
    @GetMapping("/user/{userId}/priority/{priority}")
    public ResponseEntity<List<Task>> getUserTasksByPriority(
            @PathVariable Long userId,
            @PathVariable Task.Priority priority) {
        
        List<Task> tasks = taskService.getUserTasksByPriority(userId, priority);
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 获取用户的逾期任务
     */
    @GetMapping("/user/{userId}/overdue")
    public ResponseEntity<List<Task>> getUserOverdueTasks(@PathVariable Long userId) {
        List<Task> tasks = taskService.getUserOverdueTasks(userId);
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 获取用户今日到期的任务
     */
    @GetMapping("/user/{userId}/due-today")
    public ResponseEntity<List<Task>> getUserTasksDueToday(@PathVariable Long userId) {
        List<Task> tasks = taskService.getUserTasksDueToday(userId);
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 获取用户本周到期的任务
     */
    @GetMapping("/user/{userId}/due-this-week")
    public ResponseEntity<List<Task>> getUserTasksDueThisWeek(@PathVariable Long userId) {
        List<Task> tasks = taskService.getUserTasksDueThisWeek(userId);
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 搜索用户任务
     */
    @GetMapping("/user/{userId}/search")
    public ResponseEntity<Page<Task>> searchUserTasks(
            @PathVariable Long userId,
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Task> tasks = taskService.searchUserTasks(userId, keyword, pageable);
        
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 根据标签查找任务
     */
    @GetMapping("/user/{userId}/tag/{tag}")
    public ResponseEntity<List<Task>> getUserTasksByTag(
            @PathVariable Long userId,
            @PathVariable String tag) {
        
        List<Task> tasks = taskService.getUserTasksByTag(userId, tag);
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 批量更新任务状态
     */
    @PutMapping("/batch/status")
    public ResponseEntity<?> updateTasksStatus(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Long> taskIds = (List<Long>) request.get("taskIds");
            String statusStr = (String) request.get("status");
            
            if (taskIds == null || taskIds.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("error", "任务ID列表不能为空"));
            }
            if (statusStr == null) {
                return ResponseEntity.badRequest().body(Map.of("error", "状态不能为空"));
            }
            
            Task.TaskStatus status = Task.TaskStatus.valueOf(statusStr.toUpperCase());
            taskService.updateTasksStatus(taskIds, status);
            
            return ResponseEntity.ok(Map.of("message", "批量更新任务状态成功"));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of("error", "无效的状态值"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * 批量删除任务
     */
    @DeleteMapping("/batch")
    public ResponseEntity<?> deleteTasks(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Long> taskIds = (List<Long>) request.get("taskIds");
            
            if (taskIds == null || taskIds.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("error", "任务ID列表不能为空"));
            }
            
            taskService.deleteTasks(taskIds);
            return ResponseEntity.ok(Map.of("message", "批量删除任务成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * 获取用户任务统计信息
     */
    @GetMapping("/user/{userId}/stats")
    public ResponseEntity<TaskService.TaskStats> getUserTaskStats(@PathVariable Long userId) {
        TaskService.TaskStats stats = taskService.getUserTaskStats(userId);
        return ResponseEntity.ok(stats);
    }
    
    /**
     * 获取任务完成统计（按日期）
     */
    @GetMapping("/user/{userId}/completion-stats")
    public ResponseEntity<List<Object[]>> getTaskCompletionStats(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "30") int days) {
        
        LocalDateTime startDate = LocalDateTime.now().minusDays(days);
        List<Object[]> stats = taskService.getTaskCompletionStats(userId, startDate);
        
        return ResponseEntity.ok(stats);
    }
    
    /**
     * 获取用户在指定时间范围内创建的任务
     */
    @GetMapping("/user/{userId}/created-between")
    public ResponseEntity<List<Task>> getTasksCreatedBetween(
            @PathVariable Long userId,
            @RequestParam String startDate,
            @RequestParam String endDate) {
        
        try {
            LocalDateTime start = LocalDateTime.parse(startDate);
            LocalDateTime end = LocalDateTime.parse(endDate);
            
            List<Task> tasks = taskService.getTasksCreatedBetween(userId, start, end);
            return ResponseEntity.ok(tasks);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }
    
    /**
     * 获取用户在指定时间范围内完成的任务
     */
    @GetMapping("/user/{userId}/completed-between")
    public ResponseEntity<List<Task>> getTasksCompletedBetween(
            @PathVariable Long userId,
            @RequestParam String startDate,
            @RequestParam String endDate) {
        
        try {
            LocalDateTime start = LocalDateTime.parse(startDate);
            LocalDateTime end = LocalDateTime.parse(endDate);
            
            List<Task> tasks = taskService.getTasksCompletedBetween(userId, start, end);
            return ResponseEntity.ok(tasks);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }
} 